package com.ta.service.impl;

import com.ta.mapper.CartMapper;
import com.ta.mapper.ProductMapper;
import com.ta.pojo.Cart;
import com.ta.pojo.Product;
import com.ta.pojo.User;
import com.ta.pojo.vo.CartVO;
import com.ta.service.CartService;
import com.ta.service.ex.CartException;
import com.ta.service.ex.InsertException;
import com.ta.service.ex.OrderException;
import com.ta.util.ThrowServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpSession;
import javax.smartcardio.CardException;
import java.security.PrivateKey;
import java.util.*;

@Service
public class CartServiceImpl extends ThrowServiceException implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${cart.user}")
    private String cartUser;

    /**
     * 实现添加购物车业务接口
     * @param cart
     * @param uid
     * @param userName
     */
    @Override
    public void insert(Cart cart, Integer uid, String userName) {
        /*Cart findCart = cartMapper.findByUidAndPid(uid, cart.getPid());*/
        Cart findCart = cartMapper.findByUidAndPid(uid, cart.getPid());

        Product product = productMapper.finById(cart.getPid());
        if (findCart == null) {
            cart.setUid(uid);
            cart.setCreatedUser(userName);
            cart.setCreatedTime(new Date());
            Integer row = cartMapper.insert(cart);

            /*同步redis缓存*/
            CartVO cartVO = new CartVO();
            cartVO.setCid(cart.getCid());
            cartVO.setPid(cart.getPid());
            cartVO.setImage(product.getImage());
            cartVO.setTitle(product.getTitle());
            cartVO.setNum(cart.getNum());
            cartVO.setPrice(cart.getPrice());

            redisTemplate.opsForHash().put(cartUser+"_"+uid, cart.getCid().toString(), cartVO);
            if (row != 1) {
                throw new InsertException("添加商品出现未知异常");
            }
        }else {
            Integer row = cartMapper.modifyByCid(findCart.getCid(), userName, new Date(), findCart.getNum()+cart.getNum());
            CartVO cartVO = (CartVO)redisTemplate.opsForHash().get(cartUser+"_"+uid,findCart.getCid().toString());
            cartVO.setNum(cartVO.getNum()+cart.getNum());
            redisTemplate.opsForHash().put(cartUser+"_"+uid, findCart.getCid().toString(), cartVO);
            if (row != 1) {
                throw new InsertException("添加商品出现未知异常");
            }
        }
    }

    /**
     * 实现我的购物车业务
     * @param uid
     */
    @Override
    public List<CartVO> findByUid(Integer uid) {
        String key = cartUser+"_"+uid;

        if (!redisTemplate.opsForHash().values(key).isEmpty()) {
            List<CartVO> carts = (List<CartVO>)redisTemplate.opsForHash().values(key);
            return carts;
        }

        List<CartVO> cartList = cartMapper.findByUid(uid);
        /*存储has集合*/
        HashMap<String, CartVO> map = new HashMap<>();
        for (CartVO cart : cartList) {
            map.put(cart.getCid().toString(),cart);
        }

        redisTemplate.opsForHash().putAll(key,map);
        return cartList;
    }

    /**
     * 实现购物车数量加一减一业务
     * @param cid
     * @param uid
     * @param userName
     * @param num
     */
    @Override
    public void modifyNum(Integer cid, Integer uid, String userName, Integer num) {
        throwCartNoFound(cid);
        throwCartIllegalAccess(cid,uid);
        Integer row = cartMapper.modifyByCid(cid, userName, new Date(), num);
        /*同步redis缓存*/
        CartVO cart = (CartVO) redisTemplate.opsForHash().get(cartUser+"_"+uid,cid.toString());
        cart.setNum(num);
        redisTemplate.opsForHash().put(cartUser+"_"+uid,cart.getCid().toString(),cart);
        if (row != 1) {
            throw new CartException("修改数量出现未知异常！");
        }
    }

    /**
     *实现商品结算业务
     * @param cid
     * @return
     */
    @Override
    public List<CartVO> selectCid(Integer[] cid, Integer uid) {
        if(cid == null){
            throw new CartException("结算商品为空！");
        }

        List<CartVO> cartVOList = cartMapper.findByCids(cid);
        for (CartVO cartVO : cartVOList) {
            if (!cartVO.getUid().equals(uid)) {
                throw new OrderException("购物车数据，非法访问！");
            }
        }
        return cartVOList;
    }

    /**
     * 实现购物车单个商品删除业务
     * @param cid
     * @return
     */
    @Override
    public void deleteCid(Integer cid, Integer uid) {
        Integer row = cartMapper.deleteCid(cid);
        redisTemplate.opsForHash().delete(cartUser+"_"+uid,cid.toString());
        if (row != 1) {
            throw new CartException("删除失败，出现未知异常，请联系管理员！");
        }
    }

    /**
     * 实现多个商品批量删除业务
     * @param cids
     * @return
     */
    @Override
    public void deleteCids(Integer[] cids, Integer uid) {
        Integer row = cartMapper.deleteCids(cids);
        for (Integer cid : cids) {
            redisTemplate.opsForHash().delete(cartUser+"_"+uid, cid.toString());
        }
        if (row < 1) {
            throw new CartException("删除失败，出现未知异常，请联系管理员！");
        }
    }

}
